<?php
    session_start();
    
    include('conn.php');
    $item_id = $_POST['updateItem_id'];
    
    include('verify_user.php');
    require 'anti_csrf.php';

    if (!isset($_POST['CSRFName'])) {
        trigger_error("No CSRFName found, probable invalid request.",E_USER_ERROR);
    }
    $name =$_POST['CSRFName'];
    $token=$_POST['CSRFToken'];
    if (!csrfguard_validate_token($name, $token)) {
        trigger_error("Invalid CSRF token.",E_USER_ERROR);
    }


    $query = "SELECT shops.shop_owner FROM shops INNER JOIN items ON items.item_shop=shops.shop_name WHERE items.item_id=$1";
    pg_prepare($con, 'verifyowner', $query) or die('Could not prepare verifyowner');
    $rs = pg_execute($con, 'verifyowner', array($item_id)) or die("Fail to identify item owner");
    $row = pg_fetch_assoc($rs);
     
    if($cur_user != $row['shop_owner']) {
        die("Only owner can access!");
    }
    
    $name = $_POST["updateItem_name"];
    $category = $_POST["updateItem_category"];
    $price = "$" . $_POST["updateItem_price"];
    $stock = $_POST["updateItem_stock"];
    $desc = $_POST["updateItem_desc"];
    
    //validate user inputs
    include('validate_item_inputs.php');
    
    $query = "SELECT max(id) id FROM log";
    $rs = pg_query($con, $query) or die("Could not excute query");
    $row = pg_fetch_assoc($rs);
    $id = $row['id'] + 1;
    
    $query = "UPDATE items SET item_name=$1, item_category=$2, item_desc=$3, item_price=$4, item_stock=$5 WHERE item_id=$6";
    pg_prepare($con,'prepare3',$query) or die('Could not prepare statement');
    pg_prepare($con, 'log_prepare4', 'INSERT INTO log (username, operation, object, time, id) VALUES ($1, $2, $3, $4, $5)') or die('Could not prepare log statement');
    $res1 = pg_execute($con, 'prepare3', array($name,$category,$desc,$price,$stock,$item_id)) or die('Could not execute query');
    $res2 = pg_execute($con, 'log_prepare4', array($cur_user, 'Update Item', $name, date('Y-m-d'), $id));
    
    if($res1 && $res2) {
        pg_query('COMMIT') or die('Could not commmit');
    } else {
        pg_query('ROLLBACK') or die('Could not rollback');
    }
    
    $query = "SELECT * FROM items WHERE item_name=$1";
    pg_prepare($con, 'getinfo', $query) or die('Could not prepare getinfo');
    $rs = pg_execute($con, 'getinfo', array($name)) or die('Could not execute getinfo');
    $row = pg_fetch_assoc($rs);
    $shop = $row['item_shop'];
    pg_close($con);

    header("Location:shop.php?id=" . $cur_user. "&shop=" . $shop);
?>
